//
//  LFBTabBar.m
//  LoveFreshBeen
//
//  Created by LeungChaos on 16/6/11.
//  Copyright © 2016年 xinluqi. All rights reserved.
//

#import "LFBTabBar.h"
#import "UIImage+Render.h"

@interface LFBTabBar ()

/// 中间的加号按钮
@property (nonatomic, weak) UIButton *centerBtn;

@property (nonatomic, copy) LFBTabBarCenterBtnDidClickBlock block;

/// 当前选择的按钮
@property (weak, nonatomic) UIControl *seletedBtn;

@end

@implementation LFBTabBar

+ (instancetype)tabBarWithCenterBtnDidClickBlock:(LFBTabBarCenterBtnDidClickBlock)block
{
    LFBTabBar *tb = [[self alloc]init];
    tb.block = block;
    return tb;
}

#pragma mark - 布局子控件
- (void)layoutSubviews
{
    [super layoutSubviews];
    // 遍历所有的子控件
    CGFloat btnW = self.width / self.items.count;
    
    CGFloat btnH = self.height;
    
    CGFloat btnY = 0;
    
    CGFloat btnX = 0;
    
    int i = 0;
    
    for (UIControl *obj in self.subviews) {
        
        if ([obj isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            
            [obj setFrame:CGRectMake(btnX, btnY, btnW, btnH)];
            
            [obj addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            
            // 计算x值 叠加
            btnX += btnW;
            
            obj.tag = i;
            
            if (i == 0) {
                self.seletedBtn = obj;
            }
            
            if (i == 2) {
                self.centerBtn.frame = obj.frame;
            }
            i++;
        }
        
    }

}

- (void)centerBtnClick:(UIButton *)btn
{
    if (self.block) {
        self.block (self,btn);
    }
    if ([self.boc_delegate respondsToSelector:@selector(tabBar:centerBtnDidClick:)]) {
        [self.boc_delegate tabBar:self centerBtnDidClick:btn];
    }
}

- (void)tabBarButtonClick:(UIControl *)btn
{
    if (self.seletedBtn == btn) {
        // 发消息 btn被重复点击了
        BOC__Func__
        return;
    };
    self.seletedBtn = btn;
}

#pragma mark - 懒加载
- (UIButton *)centerBtn
{
    if (_centerBtn == nil) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        [btn addTarget:self action:@selector(centerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        _centerBtn = btn;
    }
    return _centerBtn;
}

@end
